package com.ray.export.runner.imports;

import com.ray.export.empty.Empty;
import com.ray.export.exception.RunnerException;
import com.ray.export.runner.Hander;
import com.ray.export.runner.Runner;
import com.ray.export.runner.RunnerResult;
import com.ray.export.spring.ApplicationContextUtil;
import com.ray.export.strategy.data.DataModel;
import com.ray.export.strategy.file.FileContentResult;
import com.ray.export.strategy.file.HeadRead;
import com.ray.export.template.ImportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.lang.annotation.Annotation;

/**
 * @author bo shen
 * @Description: 文件上传执行者
 * @Class: FileStoreRunner
 * @Package com.ray.runner
 * @date 2019/11/21 15:00
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class HeadReadRunner implements Runner<Annotation>, Hander {

    @Override
    public RunnerResult doRunner(Annotation annotation, DataModel dataModel, RunnerResult perResult) {
        try {
           if (annotation instanceof ImportTemplate) {
                return this.hander(((ImportTemplate) annotation).headRead(), dataModel, perResult);
            }
            return this.hander(null, dataModel, perResult);
        } catch (Exception e) {
            //异常转换
            throw new RunnerException(e.getMessage(), HeadRead.class);
        }
    }

    public RunnerResult hander(Class<?> headReadClass, DataModel dataModel, RunnerResult perResult) {
        log.info("执行文件头读取");
        if (headReadClass == Empty.class) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        //判读配置是否符合规则
        if (!HeadRead.class.isAssignableFrom(headReadClass)) {
            log.error("文件头读取配置错误");
            throw new RuntimeException("文件头读取配置错误");
        }
        //获取执行对象
        HeadRead headRead = (HeadRead) ApplicationContextUtil.getApplicationContext().getBean(headReadClass);
        if (ObjectUtils.isEmpty(headRead)) {
            log.error("获取执行对象异常[{}]", headReadClass.getName());
            throw new RuntimeException("获取执行对象异常");
        }
        FileContentResult fileResult = headRead.headRead(dataModel);
        if (ObjectUtils.isEmpty(fileResult)) {
            log.error("文件头读取失败");
            throw new RuntimeException("文件头读取失败");
        }
        dataModel.setContents(fileResult.getContents());
        return new RunnerResult(HeadRead.class, dataModel, fileResult);
    }
}
